package com.sinodata.bsm.center.engine.resource.pause;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;

import com.sinodata.bsm.center.bean.RelationHelper;
import com.sinodata.bsm.center.bean.ResBean;
import com.sinodata.bsm.center.service.resource.ResPauseService;
import com.sinodata.bsm.center.service.resource.ResService;
import com.sinodata.bsm.center.util.spring.SpringContextHolder;
import com.sinodata.bsm.common.constants.ResConstants;
import com.sinodata.bsm.common.vo.Res;
import com.sinodata.bsm.common.vo.ResPauseRule;

public class ResPauseEngine extends Thread {
    private static Logger logger = Logger.getLogger(ResPauseEngine.class);
    private static ResPauseEngine instance = null;
    private final static long SLEEP_INTERVAL = 30000L;

    private ResPauseEngine() {
        logger.info("启动资源暂停");
    }

    public static ResPauseEngine getInstance() {
        if (instance == null) {
            instance = new ResPauseEngine();
        }
        return instance;
    }

    private final ResService resService = SpringContextHolder.getBean(ResService.class);
    ResPauseService pauseService = SpringContextHolder.getBean(ResPauseService.class);

    @Override
    public void run() {
        while (true) {
            try {

                Iterator<Long> it = pauseService.getPausedRuleResIds().iterator();
                Set<Long> pausedResIds = pauseService.findAllPausedResIds();
                while (it.hasNext()) {
                    Long resId = it.next();
                    Res res = resService.get(resId.longValue());
                    List<ResPauseRule> rules = pauseService.findRuleByResId(resId);
                    if (res == null) {
                        if (rules != null) {
                            for (int i = rules.size() - 1; i >= 0; i--) {
                                pauseService.deleteResPauseRule(rules.get(i).getId());
                            }
                        }
                        continue;
                    }
                    for (int i = 0; rules != null && i < rules.size(); i++) {
                        // 判断是否应该暂停此资源
                        boolean paused = pauseService.isPausedCurrently(rules.get(i));
                        if (paused) {
                            executeResourcePaused(res, pausedResIds);
                            break;
                        }
                    }

                }
                Iterator<Long> resumeIt = pausedResIds.iterator();
                while (resumeIt.hasNext()) {
                    resumeResource(resumeIt.next());
                }
            } catch (Exception e) {
                logger.error(e);
            }
            try {
                Thread.sleep(SLEEP_INTERVAL);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 
     * @param res
     * @param pausedResIds
     *            数据库中所有已暂停的资源
     */

    public void executeResourcePaused(Res res, Set<Long> pausedResIds) {
        Long resId = res.getId();
        if (pausedResIds.contains(resId.longValue())) {
            pausedResIds.remove(resId.longValue());
        }
        if (res.getPaused().intValue() != ResConstants.RES_PAUSED) {
            pauseService.setResPaused(res);
        }

        List<ResBean> beanList = RelationHelper.children(res.getId());
        for (int i = 0; i < beanList.size(); i++) {
            executeResourcePaused(beanList.get(i).res(), pausedResIds);
        }
    }

    public void resumeResource(Long resId) {
        Res res = SpringContextHolder.getBean(ResService.class).get(resId);
        SpringContextHolder.getBean(ResPauseService.class).resumeResPaused(res);
    }

}
